package jndi.ldap;

import javax.naming.Context;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Roy
 * Date: 12-1-19
 * Time: 下午10:57
 * To change this template use File | Settings | File Templates.
 */
public class LdapEnv {
    private static Properties ldapConfig;

    static {
        ClassLoader classLoader = LdapEnv.class.getClassLoader();
        InputStream in = classLoader.getResourceAsStream("JNDIConfig.properties");
        ldapConfig = new Properties();

        try {
            ldapConfig.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static final String DEFAULT_INITIAL_CONTEXT_FACTORY = ldapConfig.getProperty("context.initial.context.factory", "com.sun.jndi.ldap.LdapCtxFactory");
    public static final String DEFAULT_SECURITY_AUTHENTICATION = ldapConfig.getProperty("context.security.authentication", "simple");
    public static final String DEFAULT_REFERRAL = ldapConfig.getProperty("context.referral", "ignore");
    public static final String DEFAULT_PROVIDER_URL = ldapConfig.getProperty("context.provider.url");
    public static final String DEFAULT_SECURITY_PRINCIPAL = ldapConfig.getProperty("context.security.principal", "");
    public static final String DEFAULT_SECURITY_CREDENTIALS = ldapConfig.getProperty("context.security.credentials", "");
    private static final String DEFAULT_BASE_OBJECTS = ldapConfig.getProperty("context.baseDNs", "");

    public static synchronized Hashtable<String, String> getDefaultLdapEnv() {
        Hashtable<String, String> env = new Hashtable<String, String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT_FACTORY);
        env.put(Context.SECURITY_AUTHENTICATION, DEFAULT_SECURITY_AUTHENTICATION);
        env.put(Context.PROVIDER_URL, DEFAULT_PROVIDER_URL);
        env.put(Context.SECURITY_PRINCIPAL, DEFAULT_SECURITY_PRINCIPAL);
        env.put(Context.SECURITY_CREDENTIALS, DEFAULT_SECURITY_CREDENTIALS);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);

        return env;
    }

    public static synchronized List<String> getDefaultBaseDNs() {
        ArrayList<String> baseDNs = new ArrayList<String>();
        String[] baseDNArray = DEFAULT_BASE_OBJECTS.split(";");
        for (String baseDN : baseDNArray) {
            if (!baseDN.isEmpty()) {
                baseDNs.add(baseDN);
            }
        }

        return baseDNs;
    }
}
